angular.module('CvirtContextMenu', []).factory('ContextMenu', function($rootScope){
  var root = $('#right-click-menu'), context_menu = null;
  function find_context_menu(url){
     var context_class = ".datacenters";
      //var $scope = locals.$scope ? locals.$scope : $rootScope.$new();
      switch(true){
        case /^#\/datacenter/.test(url):
          context_class = ".datacenters";
          break;
        case /^#\/cluster\/(\d+)/.test(url):
          context_class = ".clusters";
          $rootScope.$emit('event:cluster-selected', {id: RegExp.$1});
          break;
        case /^#\/host\/(\d+)/.test(url):
          context_class = ".hosts";
          $rootScope.$emit('event:host-selected', {id: RegExp.$1});
          break;
        case /^#\/vm\/(\d+)/.test(url):
          $rootScope.$emit('event:vm-selected', {id: RegExp.$1});
          context_class = ".vms";
          break;
      }
      context_menu = root.find(context_class);
      return context_menu;
  }
  function hide_context_menu(){
    if(context_menu){
      context_menu.css({"visibility":"hidden"});
    }
    $("body").unbind("mousedown", body_mousedown);
  }
  function body_mousedown(e) {
    if (!(e.target.id == "right-click-menu" || $(e.target).parents("#right-click-menu").length > 0)) {
      context_menu.css({"visibility":"hidden"});
    }
  }
  return {
    find_context_menu: find_context_menu,
    hide_context_menu: hide_context_menu,
    body_mousedown: body_mousedown
  }
});


function ContextMenuCtrl($rootScope, $scope, Util, ContextMenu){
   $scope.add_storage = function(){
      ContextMenu.hide_context_menu();
      Util.dialog("/static/partials/storages/_storage_dialog.html", 'StorageConfigDialogCtrl', $scope, {dialogClass: 'modal mini'});
  };

  $scope.add_network = function(){
      ContextMenu.hide_context_menu();
      $scope.selected_network = {};//mock for NetworkConfigDialogCtrl
      $scope.save_method = 'create';
      Util.dialog("/static/partials/networks/_network_dialog.html", 'NetworkConfigDialogCtrl', $scope);
  }

    $scope.add_cluster = function(){
        ContextMenu.hide_context_menu();
        Util.dialog("/static/partials/clusters/_cluster_dialog.html", 'ClusterConfigDialogCtrl', $scope,{dialogClass: 'modal mini'});
  }
}

function DataCenterContextMenuCtrl($scope, Util, ContextMenu){

}
function ClusterContextMenuCtrl($rootScope, $scope, Cluster, ContextMenu,ztree,Util){
    $scope.delete = function(){
        ContextMenu.hide_context_menu();
        Util.confirm('确定要删除集群['+$scope.cluster.name+']吗?',function(){
            Cluster.delete({id:$scope.cluster.id},function(){
                ztree.deletenode('c'+$scope.cluster.id);
                ContextMenu.hide_context_menu();
            });
        })

    }
  
  $rootScope.$on('event:cluster-selected', function(e, args) {
    Cluster.get({id: args.id}, function(cluster){
      $scope.cluster = cluster;
    });
  });
};

function HostContextMenuCtrl($rootScope, $scope, Host, VM, Util, ContextMenu){
  $rootScope.$on('event:host-selected', function(e, args) {
    Host.get({id: args.id}, function(host){
      $scope.host = host;      
      
      $scope.do_start = function(){

          ContextMenu.hide_context_menu();

          if ($scope.host.powertool == null || $scope.host.powertool == 0) {

              Util.alert("此服务器没有安装远程管理卡！");
              return;
          }
          Util.confirm("确定要启动服务器吗?",function(){
              Host.start({id: [$scope.host.id]}, function() {

                    Util.alert("启动服务器成功！");
              }, function() {
                  Util.alert("启动服务器失败！");
              });
          })

      };

      $scope.do_shutdown = function(){

          ContextMenu.hide_context_menu();

          if ($scope.host.powertool == null || $scope.host.powertool == 0) {

              Util.alert("此服务器没有安装远程管理卡！");
              return;
          }

          Util.confirm("确定要关闭服务器吗?",function(){
              Host.shutdown({id: [$scope.host.id]}, function() {

              Util.alert("关闭服务器成功！");
              }, function() {
                  Util.alert("关闭服务器失败！");
              });
          });

      };

      $scope.do_reboot = function(){

          ContextMenu.hide_context_menu();

          if ($scope.host.powertool == null || $scope.host.powertool == 0) {

              Util.alert("此服务器没有安装远程管理卡！");
              return;
          }


          Util.confirm("确定要重启服务器吗?",function(){
              Host.reboot({id: [$scope.host.id]}, function() {

              Util.alert("重启服务器成功！");
              }, function() {
                  Util.alert("重启服务器失败！");
              });
          });

      };
      
            
      $scope.do_maintain = function(){

          ContextMenu.hide_context_menu();

          Host.maintain({ids: [$scope.host.id]}, function() {

          }, function() {
              Util.alert("服务器进入维护模式失败！");
          });
      }
      
      $scope.do_remove = function(){

          ContextMenu.hide_context_menu();

//          if (!$scope.host||$scope.host.instance_set.length>0||$scope.host.deleted) {
//
//              Util.alert("无法删除！");
//          }

          Util.confirm("你确定要移除主机吗，此操作将无法恢复!",function(){
              Host.remove({id:$scope.host.id},angular.noop,function(data){

                  Util.alert(data.data);

              }, function() {
                  Util.alert("删除服务器失败！");
              })
          })
      }
      
      $scope.add_vm = function(){
          ContextMenu.hide_context_menu();
          VM.authcheck(function(){
              Util.dialog("vm_workflow.html", 'VMWorkflowDialogCtrl', $scope);
          },function(data){
              Util.alert(Util.decode_error_msg(data.data));
          });
      }
      
      $scope.start_all_vms = function(){

          ContextMenu.hide_context_menu();
          Util.confirm("你确定要启动所有虚拟机吗?",function(){
              var vm_ids = $scope.host.instance_set.map(function(vm){ return vm.id; });

              VM.start({ids: vm_ids}, angular.noop, function() {
                  Util.alert("启动所有虚拟机失败！");
              });
          });

      }
      $scope.shutdown_all_vms = function(){

          ContextMenu.hide_context_menu();
          Util.confirm("你确定要关闭所有虚拟机吗?",function(){
              var vm_ids = $scope.host.instance_set.map(function(vm){ return vm.id; });

              VM.shutdown({ids: vm_ids}, angular.noop, function() {
                  Util.alert("关闭所有虚拟机失败！");
              });
          });

      }
    });
  }); 
};


function VMContextMenuCtrl($rootScope, $scope, VM, Util, ContextMenu,ztree){
  $rootScope.$on('event:vm-selected', function(e, args) {
    VM.get({id: args.id}, function(vm){
      $scope.vm = vm;
      $scope.selected_vm = vm;      
      $scope.do_edit = function() {

          ContextMenu.hide_context_menu();
        Util.dialog("/static/partials/vms/vm_config.html", 'VMConfigDialogCtrl', $scope, {backdropClick: false});
      };
      
      $scope.do_migrate = function(){

          ContextMenu.hide_context_menu();
          if($scope.vm.status!='running') {
              Util.alert('只能迁移活动的虚拟机');
          } else {
              Util.dialog("/static/partials/vms/migrate_dialog.html", 'VMMigrateDialogCtrl', $scope, {dialogClass: 'modal mini'});
          }

      };

      $scope.do_suspend = function(){

          ContextMenu.hide_context_menu();

          VM.suspend({ids: [$scope.vm.id]}, function() {

          }, function() {
              Util.alert("暂停虚拟机失败！");
          });
      };

      $scope.do_start = function(){

          ContextMenu.hide_context_menu();

          VM.start({ids: [$scope.vm.id]}, function() {

          }, function() {
              Util.alert("启动虚拟机失败！");
          });
      };

      $scope.do_reboot = function(){

          ContextMenu.hide_context_menu();

          VM.reboot({ids: [$scope.vm.id]}, function() {

          }, function() {
              Util.alert("重启虚拟机失败！");
          });
      };

      $scope.do_shutdown = function(force){
          ContextMenu.hide_context_menu();
          var resource = force ? VM.shutdown : VM.soft_shutdown;
          resource({ids: [$scope.vm.id]}, function() {

          }, function() {
              Util.alert("关闭虚拟机失败！");
          });
      };

      $scope.do_snapshot = function(){

          ContextMenu.hide_context_menu();
            if ($scope.selected_vm.status != "running") {
                Util.alert('请先启动虚拟机');
            } else
                Util.dialog("/static/partials/vms/snapshot_dialog.html", 'SnapshotDialogCtrl', $scope, {backdropClick: false, dialogClass: 'modal mini'});
      };

        $scope.do_delete = function() {

            ContextMenu.hide_context_menu();

            Util.confirm("你确定要删除吗?",function(){
                VM.delete({ids: [$scope.vm.id]},function(){
                    ztree.deletenode("v"+$scope.vm.id);
                }, function() {
                    Util.alert("删除虚拟机失败！");
                });
            })
        };

    });
  });
}